package com.stagewebserver.webserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stageuploadserver.uploadserver.pojo.UploadResponse;
import com.stageuploadserver.uploadserver.utils.MinioUtil;
import com.stagewebserver.webserver.service.DemandsService;
import com.stagecommon.common.pojo.*;
import com.stagecommon.common.utils.OrderNoUtil;
import com.stagecommon.common.vo.OrderItemVo;
import com.stagecommon.common.vo.OrdersVo;
import com.stagewebserver.webserver.mapper.DemandReceiveMapper;
import com.stagewebserver.webserver.mapper.OrderItemMapper;
import com.stagewebserver.webserver.mapper.OrdersMapper;
import com.stagewebserver.webserver.service.DemandReceiveService;
import com.stagewebserver.webserver.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;


/**
 * @author: yxl
 * @since: 2021-12-10
 **/
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private DemandsService demandsService;

    @Autowired
    private DemandReceiveService demandReceiveService;

    @Autowired
    private DemandReceiveMapper demandReceiveMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private MinioUtil minioUtil;

    @Transactional
    @Override
    public RespBean addOrder(OrderItemVo orderItem) {
        String orderCode = OrderNoUtil.getOrderCode(orderItem.getOrder().getDemandId());
        orderItem.getOrder().setOrderNum(orderCode);
        orderItem.getOrderItem().setOrderNum(orderCode);
        orderItem.getOrder().setCreateTime(LocalDateTime.now());
        if (ordersMapper.insert(orderItem.getOrder()) > 0) {
            orderItemMapper.insert(orderItem.getOrderItem());
            demandsService.update(new UpdateWrapper<Demands>().eq("demand_id", orderItem.getOrder().getDemandId()).set("status", 2));
            return RespBean.operationSuccess("生成订单成功", 200, orderItem.getOrder().getOrderNum());
        } else {
            return RespBean.operationFail("生成订单失败");
        }
    }

    @Override
    public RespBean selectPersonalOrders(String username) {
        return RespBean.operationSuccess("查询成功", 200, ordersMapper.selectOrdersByUsername(username));
    }

    @Override
    public RespBean uploadFile(MultipartFile file, Orders orders) throws Exception {

        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String fileName = "img/ordersFile/" + originalFilename;

        UploadResponse bucket01 = minioUtil.uploadFile(file, "stage", fileName);

        orders.setFilename(bucket01.getMinIoUrl());
        if ((ordersMapper.updateStatus((byte) 3, orders.getOrderId())) == 1 && (ordersMapper.updateFilename(bucket01.getMinIoUrl(), orders.getOrderNum()) == 1) && (demandReceiveMapper.updateFilename(bucket01.getMinIoUrl(), orders.getDemandId()) == 1)) {
            return RespBean.operationSuccess("上传成功", 200, orders.getFilename());
        } else return RespBean.operationFail("上传失败");
    }

    @Override
    public void downloadFile(String filename, HttpServletResponse resp) {
        {
            String filePath = System.getProperty("user.dir") + System.getProperty("file.separator")
                    + "img" + System.getProperty("file.separator") + "ordersFile";
            ;
            File file = new File(filePath);
            if (file.exists()) {
                InputStream inStream = null;
                BufferedOutputStream os = null;
                try {
                    inStream = new FileInputStream(file);
                    // 设置输出的格式，以附件的方式输出，不用用浏览器打开
                    byte[] buffer = new byte[1024];
                    int byteRead;
                    try {
                        resp.reset();
                        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
                        resp.setContentType("application/octet-stream");
                        os = new BufferedOutputStream(resp.getOutputStream());
                        while ((byteRead = inStream.read(buffer)) != -1) {
                            os.write(buffer, 0, byteRead);
                        }
                        inStream.close();
                        os.flush();
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (inStream != null) {
                            inStream.close();
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } else {
                resp.reset();
                try {
                    resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件不存在", "UTF-8"));
                    resp.setContentType("application/octet-stream");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public RespBean addRemarks(Orders orders) {
        if (ordersMapper.updateById(orders) == 1) {
            return RespBean.operationSuccess("添加成功", 200, "ok");
        }
        return RespBean.operationFail("添加失败");
    }

    @Override
    public RespBean getOrderDetailByOrderNum(String orderNum) {
        return RespBean.operationSuccess("查询成功", 200, ordersMapper.selectOrderByOrderNum(orderNum));
    }

    @Transactional
    @Override
    public RespBean updateReceiveOrder(OrdersVo orders) {
        if (ordersMapper.updateStatus((byte) 1, orders.getOrderId()) == 1) {
            demandReceiveService.insertDemandReceive(orders.getDemandReceive());
            return RespBean.operationSuccess("更新成功", 200, 1);
        }
        return RespBean.operationFail("更新失败");
    }

    @Override
    public RespBean updateRejectOrder(Orders orders) {
        orders.setStatus((byte) -1);
        if (ordersMapper.updateStatus((byte) -1, orders.getOrderId()) == 1) {
            return RespBean.operationSuccess("更新成功", 200, 1);
        }
        return RespBean.operationFail("更新失败！");
    }

    @Override
    public RespBean selectOrderDetailById(Long orderId) {
        return RespBean.operationSuccess("获取成功", 200, ordersMapper.selectOrderById(orderId));
    }
    
}
